/*
 * CustomHandlerException.java
 *
 * Copyright 2013 the original author or authors(ninglong).
 *
 * Licensed under the org.geek.common.service, Version 1.0 (the "License");
 *
 */
package org.geek.core.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.geek.core.util.JSONUtil;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

/**
 * <p>统一的异常处理</p>
 * @author ninglong bhd2973@qq.com
 * @version V1.0
 */
public class CustomHandlerException extends SimpleMappingExceptionResolver {

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		String viewName = determineViewName(ex, request);
		if (viewName != null) {
			if(!(request.getHeader("accept").indexOf("application/json")>-1||(request.getHeader("X-Requested-With")!=null&&request.getHeader("X-Requested-With").indexOf("XMLHttpRequest")>-1))){
				// Apply HTTP status code for error views, if specified.
				// Only apply it if we're processing a top-level request.
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}
				return getModelAndView(viewName, ex, request);
			}else{
				try {
					response.setContentType("application/json;charset=UTF-8");
					PrintWriter out =response.getWriter();
					Map<String,Object> map = new HashMap<String, Object>();
					map.put("success", false);
					map.put("msg", ex.getMessage());
					out.print(JSONUtil.toJson(map));
					out.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}
		}
		else {
			return null;
		}
	}
}